package com.study.spmongodb.wwj.juc.utils.executors;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author study
 * @version 1.0
 * @date 2020/12/15 10:14
 */
public class ThreadPoolExecutorBuild {

    public static void main(String[] args) throws InterruptedException {
        final ThreadPoolExecutor executor = buildThreadPoolExecutor();
        int activeCount = -1;
        int queueSize = -1;
        while (true) {
            if (activeCount != executor.getActiveCount()
                    || queueSize != executor.getQueue().size()) {
                System.out.println(executor.getActiveCount());
                System.out.println(executor.getCorePoolSize());
                System.out.println(executor.getQueue());
                System.out.println(executor.getMaximumPoolSize());
                System.out.println("---------------------------");
            }
        }
    }

    public static ThreadPoolExecutor buildThreadPoolExecutor() {
        final ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
                1, 2, 30, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(1),
                r -> {
                    final Thread thread = new Thread(r);
                    return thread;
                },
                //拒绝策略
                new ThreadPoolExecutor.AbortPolicy()
        );
        System.out.println("buildThreadPoolExecutor success");

        poolExecutor.execute(() -> sleepSeconds(1000));
        return poolExecutor;
    }

    private static void sleepSeconds(long seconds) {
        System.out.println(Thread.currentThread().getName() + " execute");
        try {
            TimeUnit.SECONDS.sleep(seconds);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
